<?php
namespace app\index\controller;

use think\Controller;
use think\Db;
use think\facade\Cache;
use think\facade\Log;
use app\service\MqttMessageHandler;

/**
 * IMEI调试控制器
 */
class ImeiDebug extends Controller
{
    /**
     * 检查指定IMEI是否存在（简化版，不使用缓存）
     */
    public function checkImei()
    {
        $imei = $this->request->param('imei', '863874074991286');

        try {
            // 1. 直接查询数据库
            $dbExists = Db::name('flow_wifi_imei')->where('IMEI', $imei)->count() > 0;

            // 2. 获取详细记录信息
            $record = Db::name('flow_wifi_imei')->where('IMEI', $imei)->find();

            return json([
                'code' => 1,
                'msg' => 'IMEI检查完成',
                'data' => [
                    'imei' => $imei,
                    'database_exists' => $dbExists,
                    'record_info' => $record ? [
                        'id' => $record['id'] ?? null,
                        'IMEI' => $record['IMEI'] ?? null,
                        'mac' => $record['mac'] ?? null,
                        'add_time' => $record['add_time'] ?? null,
                        'update_time' => $record['update_time'] ?? null
                    ] : null,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '检查失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 直接测试日志保存功能
     */
    public function testLogSave()
    {
        $imei = $this->request->param('imei', '863874074991286');
        $iccid = $this->request->param('iccid', '898608551024D1343732');

        try {
            // 模拟MQTT消息数据
            $messageData = [
                "api_version" => "1.0",
                "upload_data_type" => "normal",
                "cur_sim_id" => 2,
                "device_info" => [
                    "dev_imei1" => $imei,
                    "dev_mac" => "00:90:5B:B5:56:7E"
                ],
                "sim_info" => [
                    [
                        "sim_id" => 2,
                        "sim_exist" => 1,
                        "sim_iccid" => $iccid
                    ]
                ],
                "test_timestamp" => date('Y-m-d H:i:s'),
                "test_source" => "debug_interface"
            ];

            Log::info("开始测试日志保存: IMEI={$imei}, ICCID={$iccid}");

            // 方法1：使用模型
            $modelResult = \app\model\MqttLog::logMessage($imei, $messageData, $iccid);

            // 方法2：直接数据库操作
            $directResult = false;
            try {
                $logData = [
                    'imei' => $imei,
                    'iccid' => $iccid,
                    'content' => json_encode($messageData, JSON_UNESCAPED_UNICODE),
                    'createtime' => date('Y-m-d H:i:s')
                ];

                $directResult = Db::connect('db_config2')->name('log')->insert($logData);
            } catch (\Throwable $e) {
                Log::error("直接数据库操作失败: " . $e->getMessage());
            }

            return json([
                'code' => 1,
                'msg' => '日志保存测试完成',
                'data' => [
                    'imei' => $imei,
                    'iccid' => $iccid,
                    'model_result' => $modelResult,
                    'direct_result' => $directResult,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '测试失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 查看最近的日志记录
     */
    public function recentLogs()
    {
        $imei = $this->request->param('imei', '863874074991286');
        $limit = $this->request->param('limit', 5);
        
        try {
            $logs = Db::connect('db_config2')->name('log')
                ->where('imei', $imei)
                ->field('id,imei,iccid,createtime')
                ->order('createtime desc')
                ->limit($limit)
                ->select();
            
            return json([
                'code' => 1,
                'msg' => '查询成功',
                'data' => [
                    'imei' => $imei,
                    'total' => count($logs),
                    'logs' => $logs,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '查询失败: ' . $e->getMessage()
            ]);
        }
    }
    
    /**
     * 模拟MQTT消息处理
     */
    public function simulateMessage()
    {
        $imei = $this->request->param('imei', '863874074991286');
        
        try {
            // 模拟MQTT消息数据
            $messageData = [
                "api_version" => "1.0",
                "upload_data_type" => "normal",
                "cur_sim_id" => 2,
                "device_info" => [
                    "dev_imei1" => $imei,
                    "dev_mac" => "00:90:5B:B5:56:7E"
                ],
                "sim_info" => [
                    [
                        "sim_id" => 2,
                        "sim_exist" => 1,
                        "sim_iccid" => "898608551024D1343732"
                    ]
                ],
                "test_timestamp" => date('Y-m-d H:i:s')
            ];
            
            $topic = "tc/device/out/00905BB5567E";
            
            // 使用MqttMessageHandler处理
            $handler = new MqttMessageHandler();
            $result = $handler->handle($topic, $messageData);
            
            return json([
                'code' => 1,
                'msg' => '模拟处理完成',
                'data' => [
                    'imei' => $imei,
                    'topic' => $topic,
                    'process_result' => $result,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);
            
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '模拟处理失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 测试缓存功能
     */
    public function testCache()
    {
        try {
            $testKey = 'test_cache_' . time();
            $testValue = 'test_value_' . date('Y-m-d H:i:s');

            // 测试缓存配置
            $cacheConfig = config('cache');

            // 测试写入
            $setResult = false;
            $setError = '';
            try {
                Cache::set($testKey, $testValue, 60);
                $setResult = true;
            } catch (\Throwable $e) {
                $setError = $e->getMessage();
                // 尝试使用助手函数
                try {
                    cache($testKey, $testValue, 60);
                    $setResult = true;
                    $setError .= ' | 助手函数成功';
                } catch (\Throwable $e2) {
                    $setError .= ' | 助手函数也失败: ' . $e2->getMessage();
                }
            }

            // 测试读取
            $getValue = null;
            $getError = '';
            try {
                $getValue = Cache::get($testKey);
            } catch (\Throwable $e) {
                $getError = $e->getMessage();
                try {
                    $getValue = cache($testKey);
                    $getError .= ' | 助手函数成功';
                } catch (\Throwable $e2) {
                    $getError .= ' | 助手函数也失败: ' . $e2->getMessage();
                }
            }

            // 检查runtime/cache目录权限
            $cacheDir = app()->getRuntimePath() . 'cache';
            $cacheDirExists = is_dir($cacheDir);
            $cacheDirWritable = is_writable($cacheDir);

            return json([
                'code' => 1,
                'msg' => '缓存测试完成',
                'data' => [
                    'cache_config' => $cacheConfig,
                    'test_key' => $testKey,
                    'test_value' => $testValue,
                    'set_result' => $setResult,
                    'set_error' => $setError,
                    'get_value' => $getValue,
                    'get_error' => $getError,
                    'cache_dir' => $cacheDir,
                    'cache_dir_exists' => $cacheDirExists,
                    'cache_dir_writable' => $cacheDirWritable,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '缓存测试失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 强制刷新IMEI缓存
     */
    public function refreshImeiCache()
    {
        $imei = $this->request->param('imei', '863874074991286');

        try {
            // 1. 清除旧缓存
            $cacheKey = 'imei_exists:' . $imei;
            Cache::rm($cacheKey);

            // 2. 直接查询数据库
            $dbExists = Db::name('flow_wifi_imei')->where('IMEI', $imei)->count() > 0;

            // 3. 设置新缓存
            Cache::set($cacheKey, $dbExists ? 1 : 0, 1800);

            // 4. 验证缓存
            $newCached = Cache::get($cacheKey);

            return json([
                'code' => 1,
                'msg' => 'IMEI缓存已刷新',
                'data' => [
                    'imei' => $imei,
                    'database_exists' => $dbExists,
                    'new_cache_value' => $newCached,
                    'cache_key' => $cacheKey,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '刷新缓存失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 检查Redis环境
     */
    public function checkRedis()
    {
        try {
            $result = [
                'php_redis_extension' => extension_loaded('redis'),
                'php_redis_version' => extension_loaded('redis') ? phpversion('redis') : 'Not installed',
                'cache_config' => config('cache'),
                'thinkphp_version' => \think\App::VERSION ?? 'Unknown'
            ];

            // 测试原生Redis连接
            if (extension_loaded('redis')) {
                try {
                    $redis = new \Redis();
                    $redis->connect('127.0.0.1', 6379);
                    if (!empty('qazEdc')) {
                        $redis->auth('qazEdc');
                    }
                    $redis->set('test_key', 'test_value');
                    $testValue = $redis->get('test_key');
                    $redis->del('test_key');
                    $redis->close();

                    $result['native_redis_test'] = [
                        'success' => true,
                        'test_value' => $testValue
                    ];
                } catch (\Throwable $e) {
                    $result['native_redis_test'] = [
                        'success' => false,
                        'error' => $e->getMessage()
                    ];
                }
            }

            // 测试ThinkPHP Cache
            try {
                Cache::set('tp_test_key', 'tp_test_value', 60);
                $tpTestValue = Cache::get('tp_test_key');
                Cache::rm('tp_test_key');

                $result['thinkphp_cache_test'] = [
                    'success' => true,
                    'test_value' => $tpTestValue
                ];
            } catch (\Throwable $e) {
                $result['thinkphp_cache_test'] = [
                    'success' => false,
                    'error' => $e->getMessage()
                ];
            }

            return json([
                'code' => 1,
                'msg' => 'Redis环境检查完成',
                'data' => $result
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '检查失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 深度诊断Redis问题
     */
    public function diagnoseRedis()
    {
        try {
            $result = [];

            // 1. 检查配置
            $cacheConfig = config('cache');
            $result['cache_config'] = $cacheConfig;

            // 2. 测试不同的Cache调用方式
            $testKey = 'diagnose_test_' . time();

            // 方式1: Cache::get/set
            try {
                \think\facade\Cache::set($testKey . '_1', 'test1', 60);
                $value1 = \think\facade\Cache::get($testKey . '_1');
                \think\facade\Cache::rm($testKey . '_1');
                $result['facade_cache'] = ['success' => true, 'value' => $value1];
            } catch (\Throwable $e) {
                $result['facade_cache'] = ['success' => false, 'error' => $e->getMessage()];
            }

            // 方式2: cache() 助手函数
            try {
                cache($testKey . '_2', 'test2', 60);
                $value2 = cache($testKey . '_2');
                cache($testKey . '_2', null);
                $result['helper_cache'] = ['success' => true, 'value' => $value2];
            } catch (\Throwable $e) {
                $result['helper_cache'] = ['success' => false, 'error' => $e->getMessage()];
            }

            // 方式3: 直接实例化Cache
            try {
                $cache = \think\Cache::init($cacheConfig);
                $cache->set($testKey . '_3', 'test3', 60);
                $value3 = $cache->get($testKey . '_3');
                $cache->rm($testKey . '_3');
                $result['direct_cache'] = ['success' => true, 'value' => $value3];
            } catch (\Throwable $e) {
                $result['direct_cache'] = ['success' => false, 'error' => $e->getMessage()];
            }

            // 4. 模拟MqttMessageHandler中的调用
            try {
                $handler = new \app\service\MqttMessageHandler();
                $testResult = $handler->forceCheckImeiExists('test_imei_123');
                $result['mqtt_handler_test'] = ['success' => true, 'result' => $testResult];
            } catch (\Throwable $e) {
                $result['mqtt_handler_test'] = ['success' => false, 'error' => $e->getMessage()];
            }

            // 5. 检查Redis服务状态
            try {
                $redis = new \Redis();
                $redis->connect('127.0.0.1', 6379);
                if (!empty('qazEdc')) {
                    $redis->auth('qazEdc');
                }
                $redis->ping();
                $info = $redis->info();
                $redis->close();
                $result['redis_service'] = [
                    'success' => true,
                    'version' => $info['redis_version'] ?? 'unknown',
                    'connected_clients' => $info['connected_clients'] ?? 'unknown'
                ];
            } catch (\Throwable $e) {
                $result['redis_service'] = ['success' => false, 'error' => $e->getMessage()];
            }

            return json([
                'code' => 1,
                'msg' => 'Redis深度诊断完成',
                'data' => $result
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '诊断失败: ' . $e->getMessage()
            ]);
        }
    }
}
